<template>
    <el-card>
        <template #header>
            <h3>医疗机构信息</h3>
        </template>
        <!-- 搜索区域 -->
        <el-button type="primary" class="add" @click="showAddWindow()">添加医疗机构</el-button>
        <el-form inline>
            <el-form-item label="医疗机构" style="width: 250px">
                <el-autocomplete v-model="params.name" value-key="name" :fetch-suggestions="querySearch" clearable
                    class="inline-input w-50" placeholder="" @select="handleSelect" @input="clear" />
            </el-form-item>
            <el-form-item label="类型" style="width: 150px">
                <el-autocomplete v-model="params.institutionType" value-key="name"
                    :fetch-suggestions="querySearchInstitutionType" clearable class="inline-input w-50" placeholder=""
                    @select="handleSelectInstitutionType" @input="clearInstitutionType" />
            </el-form-item>
            <el-form-item label="等级" style="width: 140px">
                <el-select v-model="params.level" placeholder="">
                    <el-option v-for="item in levelOptions" :key="item.value" :label="item.label" :value="item.value">
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="地址" style="width: 200px">
                <el-input v-model="params.address"></el-input>
            </el-form-item>
            <el-form-item label="联系方式" style="width: 180px">
                <el-input v-model="params.contact"></el-input>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="searchHealthInstitutions()">搜索</el-button>
            </el-form-item>
        </el-form>
        <!-- 表格区域 -->
        <el-table :data="healthInstitutions" border @sort-change="handleSortChange">
            <el-table-column label="图片" align="center" width="180">
                <template #default="scope">
                    <el-image v-if="scope.row.institution_img" :src="scope.row.institution_img"
                        class="row-institution-img"></el-image>
                    <el-image v-else src="src\assets\imgs\暂无图片.png" class="row-institution-img"></el-image>
                </template>
            </el-table-column>
            <el-table-column label="名称" prop="name" sortable="custom" align="center" width="180"></el-table-column>
            <el-table-column label="类型" prop="type" sortable="custom" align="center"></el-table-column>
            <el-table-column label="等级" prop="level" sortable="custom" align="center">
                <template #default="scope">
                    {{ levelText(scope.row.level) }}
                </template>
            </el-table-column>
            <el-table-column label="地址" prop="address" sortable="custom" align="center" width="300"></el-table-column>
            <el-table-column label="联系方式" prop="contact" sortable="custom" align="center" width="120"></el-table-column>
            <el-table-column label="操作" align="center" width="210">
                <template #default="scope">
                    <el-button type="primary" @click="showEditWindow(scope.row)" class="btn">编辑</el-button>
                    <!-- 删除确认气泡 -->
                    <el-popconfirm width="250" icon-color="#626AEF" title="确认删除该医疗机构吗？">
                        <template #reference>
                            <el-button type="danger" class="btn">删除</el-button>
                        </template>
                        <template #actions="{ confirm, cancel }">
                            <el-button size="small" @click.once="cancel">取消</el-button>
                            <el-button type="danger" size="small"
                                @click.once="deleteHealthInstitution(scope.row, confirm)">
                                确认
                            </el-button>
                        </template>
                    </el-popconfirm>
                    <el-button type="primary" @click="this.$router.push('/institutionDevice/' + scope.row.id)"
                        class="btn">医疗器械</el-button>
                    <el-button type="primary" @click="this.$router.push('/institutionMedication/' + scope.row.id)"
                        class="btn">药品</el-button>
                </template>
            </el-table-column>
        </el-table>
        <!-- 分页区域 -->
        <el-pagination v-if="params.total > 0" :current-page="params.currentPage" :page-size="params.pageSize"
            background layout="total, prev, pager, next" :total="params.total" @current-change="handleCurrentChange" />
    </el-card>
    <!-- 医疗机构信息编辑弹窗 -->
    <el-dialog v-model="showEdit" title="医疗机构信息" width="500" @close="closeWindow">
        <el-form :model="row" label-width="120px" :rules="rules" ref="rowForm">
            <!-- 上传图片 -->
            <el-form-item label="图片" prop="avatar">
                <el-upload class="avatar-uploader" action="http://127.0.0.1:8082/upload" :show-file-list="false"
                    :on-success="handleAvatarSuccess">
                    <el-image v-if="row.institution_img" :src="row.institution_img" class="institution-img"></el-image>
                    <el-icon v-else class="avatar-uploader-icon">
                        <Plus />
                    </el-icon>
                </el-upload>
            </el-form-item>
            <el-form-item label="名称" prop="name">
                <el-input v-model="row.name"></el-input>
            </el-form-item>
            <el-form-item label="类型" prop="institutionTypeId">
                <el-autocomplete v-model="row.type" value-key="name" :fetch-suggestions="querySearchInstitutionType"
                    clearable class="inline-input w-50" placeholder="" @select="handleSelectInstitutionType"
                    @input="clearInstitutionType" />
            </el-form-item>
            <el-form-item label="等级" prop="level">
                <el-select v-model="row.levelName" placeholder="请选择等级">
                    <el-option v-for="item in levelOptions" :key="item.value" :label="item.label" :value="item.value"
                        @click="row.level = item.value;">
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="地址" prop="address">
                <el-input v-model="row.address"></el-input>
            </el-form-item>
            <el-form-item label="简介" prop="manager" v-if="!showAdd">
                <el-input v-model="row.description" :autosize="{ minRows: 2, maxRows: 4 }" type="textarea" />
            </el-form-item>
            <el-form-item label="联系方式" prop="contact">
                <el-input v-model="row.contact"></el-input>
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button v-if="!showAdd" type="primary" @click="updateHealthInstitution(row)">保存</el-button>
                <el-button v-if="showAdd" type="primary" @click="addHealthInstitution(row)">添加</el-button>
                <el-button @click="showEdit = false">取消</el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script>
import { healthInstitutionAddAPI, healthInstitutionFindAPI, healthInstitutionUpdateAPI, healthInstitutionDeleteAPI, healthInstitutionsFindAPI } from '@/api/healthInstitution';
import { institutionTypeFindAPI } from '@/api/institutionType';
import { ElMessage } from 'element-plus';
export default {
    data() {
        return {
            params: {
                // 搜索关键词
                name: '',
                institutionTypeId: '',
                level: '',
                address: '',
                contact: '',
                // 分页参数
                total: 0,
                currentPage: 1,
                pageSize: 7
            },
            healthInstitutionDropDown: [],
            healthInstitutions: [],
            institutionTypesDropDown: [],
            showEdit: false,
            showAdd: false,
            row: {},
            rules: {
                name: { required: true, message: '名称不能为空', trigger: 'blur' },
                institutionTypeId: { required: true, message: '类型不能为空', trigger: ['blur', 'change'] },
                level: { required: true, message: '等级不能为空', trigger: 'blur' },
                address: { required: true, message: '地址不能为空', trigger: 'blur' },
                contact: { required: true, message: '联系方式不能为空', trigger: 'blur' },
            },
            levelOptions: [
                // 0三级特等、1三级甲等、2三级乙等、3三级丙等
                // 4二级甲等、5二级乙等、6二级丙等
                // 7一级甲等、8一级乙等、9一级丙等
                // 10其他
                {
                    value: '',
                    label: '全部'
                },
                {
                    value: '0',
                    label: '三级特等'
                },
                {
                    value: '1',
                    label: '三级甲等'
                },
                {
                    value: '2',
                    label: '三级乙等'
                },
                {
                    value: '3',
                    label: '三级丙等'
                },
                {
                    value: '4',
                    label: '二级甲等'
                },
                {
                    value: '5',
                    label: '二级乙等'
                },
                {
                    value: '6',
                    label: '二级丙等'
                },
                {
                    value: '7',
                    label: '一级甲等'
                },
                {
                    value: '8',
                    label: '一级乙等'
                },
                {
                    value: '9',
                    label: '一级丙等'
                },
                {
                    value: '10',
                    label: '其他'
                }
            ],
        }
    },
    methods: {
        loadHealthInstitutionInfoList() {
            healthInstitutionsFindAPI(this.params).then((resp) => {
                if (resp.data.code == 2000) {
                    this.healthInstitutions = resp.data.datas;
                    this.params.total = resp.data.total;
                } else {
                    ElMessage.error(resp.data.message);
                }
            })
        },
        loadHealthInstitutionDropDownList() {
            healthInstitutionFindAPI(this.params).then((resp) => {
                if (resp.data.code == 2000) {
                    this.healthInstitutionDropDown = resp.data.datas;
                } else {
                    ElMessage.error(resp.data.message);
                }
            })
        },
        loadInstitutionTypesDropDownList() {
            institutionTypeFindAPI(this.params).then((resp) => {
                if (resp.data.code == 2000) {
                    this.typesDropDown = resp.data.datas;
                } else {
                    ElMessage.error(resp.data.message);
                }
            })
        },
        searchHealthInstitutions() {
            this.loadHealthInstitutionInfoList();
        },
        handleCurrentChange(page) {
            this.params.currentPage = page;
            this.loadHealthInstitutionInfoList();
        },
        // 图片上传成功之后回调函数
        handleAvatarSuccess(response) {
            this.row.institution_img = response;
        },
        showEditWindow(row) {
            this.row = JSON.parse(JSON.stringify(row));
            this.params.institutionTypeId = row.type_id;
            this.row.levelName = this.levelText(row.level);
            this.showEdit = true;
        },
        updateHealthInstitution(row) {
            this.$refs.rowForm.validate((val) => {
                if (val) {
                    healthInstitutionUpdateAPI(row).then((resp) => {
                        if (resp.data.code == 2000) {
                            this.params.iid = '';
                            this.params.institutionTypeId = '';
                            this.showEdit = false;
                            this.loadHealthInstitutionInfoList();
                            ElMessage.success(resp.data.message);
                        } else {
                            ElMessage.error(resp.data.message);
                        }
                    })
                }
            })
        },
        deleteHealthInstitution(row, confirm) {
            healthInstitutionDeleteAPI(row).then((resp) => {
                if (resp.data.code == 2000) {
                    this.loadHealthInstitutionInfoList();
                    ElMessage.success(resp.data.message);
                } else {
                    ElMessage.error(resp.data.message);
                }
            })
            confirm();
        },
        showAddWindow() {
            this.row = {};
            this.showEdit = true;
            this.showAdd = true;
        },
        addHealthInstitution(row) {
            row.role = 2;
            this.$refs.rowForm.validate((val) => {
                if (val) {
                    healthInstitutionAddAPI(row).then((resp) => {
                        if (resp.data.code == 2000) {
                            this.params.institutionTypeId = '';
                            this.loadHealthInstitutionInfoList();
                            this.showEdit = false;
                            this.showAdd = false;
                            ElMessage.success(resp.data.message);
                        } else {
                            ElMessage.error(resp.data.message);
                        }
                    })
                }
            })
        },
        closeWindow() {
            this.loadHealthInstitutionInfoList();
            this.showEdit = false;
            this.showAdd = false;
            this.params.institutionTypeId = '';
        },
        //该方法选择列表后触发
        handleSelect(item) {
            this.params.iid = item.id;
            this.row.id = item.id;
        },
        //输入框获取焦点时调用的方法
        querySearch(queryString, cb) {
            let results = this.healthInstitutionDropDown;
            results = queryString
                ? results.filter(this.createFilter(queryString))
                : results;
            cb(results);
        },
        //这是当输入数据时触发的，筛选出和输入数据匹配的建议输入。
        createFilter(queryString) {
            return (institution) => {
                // 确保 institution 是一个字符串或对象
                if (typeof institution === 'object') {
                    return JSON.stringify(institution).toLowerCase().indexOf(queryString.toLowerCase()) > -1;
                }
                return institution.toLowerCase().indexOf(queryString.toLowerCase()) > -1;
            };
        },
        //点击清除按钮时触发事件
        clear() {
            this.params.iid = '';
        },

        // 医疗机构类型选择
        //该方法选择列表后触发
        handleSelectInstitutionType(item) {
            this.params.institutionTypeId = item.id;
            this.row.institutionTypeId = item.id;
        },
        //输入框获取焦点时调用的方法
        querySearchInstitutionType(queryString, cb) {
            let results = this.typesDropDown;
            results = queryString
                ? results.filter(this.createFilterInstitutionType(queryString))
                : results;
            cb(results);
        },
        //这是当输入数据时触发的，筛选出和输入数据匹配的建议输入。
        createFilterInstitutionType(queryString) {
            return (institutionType) => {
                // 确保 level 是一个字符串或对象
                if (typeof institutionType === 'object') {
                    return JSON.stringify(institutionType).toLowerCase().indexOf(queryString.toLowerCase()) > -1;
                }
                return level.toLowerCase().indexOf(queryString.toLowerCase()) > -1;
            };
        },
        //点击清除按钮时触发事件
        clearInstitutionType() {
            this.params.institutionTypeId = '';
        },
        levelText(level) {
            switch (level) {
                case 0:
                    return '三级特等';
                case 1:
                    return '三级甲等';
                case 2:
                    return '三级乙等';
                case 3:
                    return '三级丙等';
                case 4:
                    return '二级甲等';
                case 5:
                    return '二级乙等';
                case 6:
                    return '二级丙等';
                case 7:
                    return '一级甲等';
                case 8:
                    return '一级乙等';
                case 9:
                    return '一级丙等';
                case 10:
                    return '其他';
            }
        },
        handleSortChange({ prop, order }) {
            if (order) {
                // 根据 prop 和 order 进行排序
                this.params.sortProp = prop;
                this.params.sortOrder = order === 'ascending' ? 'asc' : 'desc';
                this.loadHealthInstitutionInfoList();
            } else {
                // 清除排序
                delete this.params.sortProp;
                delete this.params.sortOrder;
                this.loadHealthInstitutionInfoList();
            }
        }
    },
    created() {
        this.loadHealthInstitutionInfoList();
        this.loadHealthInstitutionDropDownList();
        this.loadInstitutionTypesDropDownList();
    }
}
</script>

<style scoped>
.el-pagination {
    margin: 20px 0 0 450px;
    align-items: center;
}

.avatar-uploader .avatar {
    width: 178px;
    height: 178px;
    display: block;
}

.avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
}

.institution-img {
    width: 300px;
    height: 200px;
}

.add {
    position: relative;
    top: -10px;
}

.row-institution-img {
    width: 150px;
    height: 100px;
}

.btn {
    margin: 5px;
    width: 80px;
}
</style>